//
//  GroupIndentCommentViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/26.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "GroupIndentCommentViewController.h"
#import "PhotoSheetView.h"
#import "UICustomActionSheet.h"
#import "STActionSheet.h"
#import "DZNPhotoEditorViewController.h"
#import "UIImagePickerController+Edit.h"
#import "UIImageView+WebCache.h"
#import <UIImageView+RJLoader.h>
#import "PhotoPopView.h"

@interface GroupIndentCommentViewController ()<UITextViewDelegate>
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UITextView *textview;
@property (strong, nonatomic) IBOutlet UILabel *placeHolder;
@property (strong, nonatomic) IBOutlet UIButton *addPhotoButton;
@property (strong, nonatomic) IBOutlet UIButton *ifShowNameButton;
@property(nonatomic,assign)CGFloat totalScore;
@property(nonatomic,strong)NSMutableDictionary * photoDic;
@property(nonatomic,strong)NSString * showOrNot;
@property(nonatomic,assign)NSInteger  currentIndexpath;
@end

@implementation GroupIndentCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     _showOrNot = @"1";
    _currentIndexpath = 0;
    _photoDic = [NSMutableDictionary dictionary];
    _totalScore = 10;
    [self initViewLayout];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 460), YES);
    
    StarsView * startView = [[StarsView alloc]initWithFrame:flexibleFrame(CGRectMake(2, 317, 235, 24), YES) Title:@"综合评分" numberOfStars:5 complect:^(CGFloat index) {
        
    }];
    [_scroView addSubview:startView];
    
    _textview.delegate = self;
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma mark == 发布评论
- (IBAction)commitComment:(id)sender {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:_textview.text forKey:@"content"];
    NSString * images = @"";
    if (_currentIndexpath==0) {
         [dic setObject:@"" forKey:@"CommtImg"];
    }else{
    for (int i=0; i<_currentIndexpath+1; i++) {
        NSString * image = _photoDic[[NSString stringWithFormat:@",%d",i]];
        if (i==0) {
            image = _photoDic[[NSString stringWithFormat:@"%d",i]];
        }
        images = [images stringByAppendingString:image];
    }
         [dic setObject:images forKey:@"CommtImg"];
    }
   
    [dic setObject:@"" forKey:@"mgcoOrderDetailId"];
    
    [dic setObject:[NSString stringWithFormat:@"%ld",(NSInteger)_totalScore*2] forKey:@"CommentStars"];
     [dic setObject:@"10" forKey:@"CommentLevel"];
    [dic setObject:_showOrNot forKey:@"mgcoIsAnonymous"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_insertComment withHttpType:@"POST" withTag:SX_SX_insertComment];
}
- (IBAction)addPhoto:(id)sender {

    
    if (_photoDic.allValues.count>=3) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片不能超过三张" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alterView show];
        return;
    }
    

        PhotoPopView * photoPopView = [[PhotoPopView alloc]initWithcomplect:^(NSInteger index) {
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                __weak __typeof(self)weakSelf = self;
                if (index == 0){
                    controller.allowsEditing = YES;
                    controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                    controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                    
                    controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                        
                        UIImage *image = info[UIImagePickerControllerEditedImage];
                        UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                        imageButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 235, 60, 60), YES);
                        [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                        [_scroView addSubview:imageButton];
                        [self imageUpload:1 :image];
                        // Dismiss when the crop mode was disabled
                        if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                            [weakSelf dismissViewControllerAnimated:NO completion:^{
                            }];
                        }
                    };
                    
                    controller.cancellationBlock = ^(UIImagePickerController *picker) {
                        
                        // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                        if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                            [weakSelf dismissViewControllerAnimated:NO completion:^{
                            }];
                        }
                        else {
                            picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                            [picker popViewControllerAnimated:YES];
                        }
                    };
                    [self presentViewController:controller animated:NO completion:^{}];
                }else if (index == 1){
                    controller.allowsEditing = YES;
                    controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                    
                    controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                        
                        UIImage *image = info[UIImagePickerControllerEditedImage];
                        UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                        imageButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 235, 60, 60), YES);
                        [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                        [_scroView addSubview:imageButton];
                        [self imageUpload:1 :image];
                        // Dismiss when the crop mode was disabled
                        if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                            [weakSelf dismissViewControllerAnimated:NO completion:^{
                            }];
                        }
                    };
                    
                    controller.cancellationBlock = ^(UIImagePickerController *picker) {
                        
                        // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                        if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                            [weakSelf dismissViewControllerAnimated:NO completion:^{
                            }];
                        }
                        else {
                            picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                            [picker popViewControllerAnimated:YES];
                        }
                    };
                    [self presentViewController:controller animated:NO completion:^{}];
                }
                
                
                
                
            }else {
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                __weak __typeof(self)weakSelf = self;
                if (index == 0){
                    controller.allowsEditing = YES;
                    controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                    controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                    
                    controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                        
                        UIImage *image = info[UIImagePickerControllerEditedImage];
                        UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                        imageButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 235, 60, 60), YES);
                        [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                        [_scroView addSubview:imageButton];
                        [self imageUpload:1 :image];
                        // Dismiss when the crop mode was disabled
                        if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                            [weakSelf dismissViewControllerAnimated:NO completion:^{
                            }];
                        }
                    };
                    
                    controller.cancellationBlock = ^(UIImagePickerController *picker) {
                        
                        // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                        if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                            [weakSelf dismissViewControllerAnimated:NO completion:^{
                            }];
                        }
                        else {
                            picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                            [picker popViewControllerAnimated:YES];
                        }
                    };
                    [self presentViewController:controller animated:NO completion:^{}];
                }else if (index == 1){
                    controller.allowsEditing = YES;
                    controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                    
                    controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                        
                        UIImage *image = info[UIImagePickerControllerEditedImage];
                        UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                        imageButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 235, 60, 60), YES);
                        [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                        [_scroView addSubview:imageButton];
                        [self imageUpload:1 :image];
                        // Dismiss when the crop mode was disabled
                        if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                            [weakSelf dismissViewControllerAnimated:NO completion:^{
                            }];
                        }
                    };
                    
                    controller.cancellationBlock = ^(UIImagePickerController *picker) {
                        
                        // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                        if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                            [weakSelf dismissViewControllerAnimated:NO completion:^{
                            }];
                        }
                        else {
                            picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                            [picker popViewControllerAnimated:YES];
                        }
                    };
                    [self presentViewController:controller animated:NO completion:^{}];
                }
                
            }
            
        }];
        [photoPopView show];
    
    
}

- (IBAction)showNameOrNot:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _showOrNot = @"1";
    }else{
        _showOrNot = @"0";
    }
}

#pragma mark - 上传图片--------------------------
- (void) imageUpload:(int)numberImg:(UIImage *)imageImage{
    NSString *url = SX_uploadCommentImg;
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    CGSize newSize = CGSizeMake(50, 50);
    UIGraphicsBeginImageContext(newSize);
    [imageImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData* data  = UIImageJPEGRepresentation(newImage, 0.5);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //设置HTTPHeader中Content-Type的值
    NSString* content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    //    [body appendFormat:@"Content-Type: %@\r\n\r\n",content];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *headerUserAgent=@"";
    if ([Common getLoginStatus]) {
        NSString *userName = [[Common getLoginInfo] objectForKey:Key_User_nickname];
        NSString *userId  = [NSString stringWithFormat:@"%@",[[Common getLoginInfo] objectForKey:Key_User_userId]];
        NSString *encryptPwd  = [Common shaEncrypt:[[Common getLoginInfo] objectForKey:Key_User_password]];
        NSString *localUserIdentify  = [[UIDevice currentDevice].identifierForVendor UUIDString];
        headerUserAgent = [NSString stringWithFormat:@"%@|%@|%@|%@",userName,userId,encryptPwd,localUserIdentify];
    }else{
        headerUserAgent = @"|||";
    }
    
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置User-Agent
    [request setValue:headerUserAgent forHTTPHeaderField:@"User-Agent"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    //上传文件开始
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //获得返回值
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
    
    //取得返回的图片名
    //    NSArray* array = [returnString componentsSeparatedByString:@"###"];
    NSString * image = [NSString stringWithFormat:@"%@", dictionary[@"result"][0][@"simaId"]];
    
    [_photoDic setObject:image forKey:[NSString stringWithFormat:@"%ld",_currentIndexpath]];
    _currentIndexpath +=1;
    _addPhotoButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 235, 60, 60), YES);
    
    
    
}


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    _placeHolder.hidden = YES;
    
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    if (_textview.text.length>0) {
        _placeHolder.hidden = YES;
    }else{
        _placeHolder.hidden = NO;
    }
    return YES;
}




#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    
    if (tag==SX_SX_insertComment) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            [self.navigationController  popViewControllerAnimated:YES];
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  ];
          
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
